//
//  SimpleDiskCache.m
//  SimpleWebImage
//
//  Created by Jiang on 2019/8/26.
//  Copyright © 2019 SilverFruity. All rights reserved.
//

#import "SimpleDiskCache.h"

@implementation SimpleDiskCache
{
    NSString *_diskCacheDirectory;
}
- (instancetype)init
{
    self = [super init];
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    path = [path stringByAppendingPathComponent:@"SimpleImageCache"];
    _diskCacheDirectory = path;
    NSLog(@"%@",path);
    [self createFileDirectory:_diskCacheDirectory];
    return self;
}
- (nullable UIImage *)imageForKey:(nonnull NSString *)key {
    if ([[NSFileManager  defaultManager] fileExistsAtPath:[self cachePathForKey:key]]) {
        return [UIImage imageWithContentsOfFile:[self cachePathForKey:key]];
    }
    return nil;
}

- (BOOL)saveImage:(UIImage *)image forKey:(NSString *)key{
    if (!image) {
        return NO;
    }
    NSData *data = UIImagePNGRepresentation(image);
    if (data) {
        data = UIImageJPEGRepresentation(image, 1.0);
    }
    [data writeToFile:[self cachePathForKey:key] atomically:YES];
    return YES;
}
- (NSString *)cachePathForKey:(NSString *)key{
    return [_diskCacheDirectory stringByAppendingPathComponent:key];
}
- (void)createFileDirectory:(NSString *)dir{
    if (![[NSFileManager defaultManager] fileExistsAtPath:dir]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
    }
}
- (void)removeImageForKey:(NSString *)key{
    NSString *path  = [self cachePathForKey:key];
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

@end
